/*
 * @Description: 异步状态刷新
 * @Author: chenju
 * @Date: 2022-11-14 10:13:04
 * @LastEditors: chenju
 * @LastEditTime: 2022-12-14 14:05:45
 */
import { ref, Ref, onUnmounted } from 'vue';

export interface RefreshStatusNumberInfo {
  // 当前已成功数值
  current: number;
  // 总数值
  total: number;
  // 是否正在刷新
  refreshing: boolean;
}

interface UseAsyncStatusRefreshWidthProgressResult {
  // 最终的状态（过程中true，没异步任务或者任务完成false）
  isRefreshing: Ref<boolean>;
  // 进度
  refreshStatusNumber: Ref<RefreshStatusNumberInfo>;
  // 开始执行刷新时的初始进度
  defaultNumber: Ref<Omit<RefreshStatusNumberInfo, 'refreshing'>>;
  // 开始刷新异步状态的方法
  handleStartRefresh: (params?: any) => void;
}

/**
 * 异步状态刷新
 * @param statusRefreshApi 接口请求方法，返回值为Promise<boolean>
 * @param successCallback 刷新成功后的回调方法
 * @returns
 */
export const useAsyncStatusRefreshWidthProgress = (
  statusRefreshApi: () => Promise<RefreshStatusNumberInfo>,
  successCallback: (params?: any) => void,
  loopGap = 2000
): UseAsyncStatusRefreshWidthProgressResult => {
  // 是否正在刷新
  const isRefreshing = ref<boolean>(false);
  const refreshStatusNumber = ref<RefreshStatusNumberInfo>({
    current: 0,
    total: 0,
    refreshing: false
  });
  // 开始执行刷新时的初始进度
  const defaultNumber = ref<Omit<RefreshStatusNumberInfo, 'refreshing'>>({
    current: 0,
    total: 0
  });
  // 是否需要触发成功回调（进入页面时在刷新中的或者主动触发刷新的）
  const needShowSuccessCallback = ref(false);
  // 状态刷新定时器
  let refreshingTimer: any;
  // 刷新成功后的回调方法的入参
  const successCallbackParams = ref<any>();
  // 状态接口请求操作
  async function getStatusReq(inLoop = false) {
    try {
      const res = await statusRefreshApi();
      console.log('progress-button statusRefreshApi res', res);
      // 设置默认值，仅在接口返回刷新并且页面未刷新时触发
      if (res.refreshing && !isRefreshing.value) {
        defaultNumber.value = {
          current: res.current,
          total: res.total
        };
      }
      refreshStatusNumber.value = res;
      isRefreshing.value = res.refreshing;
      if (isRefreshing.value && needShowSuccessCallback.value === false)
        needShowSuccessCallback.value = true;
      if (isRefreshing.value === false && needShowSuccessCallback.value) {
        needShowSuccessCallback.value = false;
        successCallback(successCallbackParams.value);
      }
      if (!inLoop) {
        getSendStatusLoop();
      }
    } catch (error) {
      isRefreshing.value = false;
      initProgress();
      console.log('error', error);
    }
  }
  // 消息发送状态循环生成方法
  function getSendStatusLoop() {
    refreshingTimer = setInterval(() => {
      console.log('percent loop', loopGap);
      if (isRefreshing.value === true) {
        getStatusReq(true);
      } else {
        clearInterval(refreshingTimer);
        refreshingTimer = null;
      }
    }, loopGap);
  }

  // 开始刷新状态
  function handleStartRefresh(params?: any) {
    successCallbackParams.value = params;
    isRefreshing.value = true;
    needShowSuccessCallback.value = true;
    // 初始化进度的取值
    initProgress();
    getStatusReq();
  }

  // 初始化进度的取值
  function initProgress() {
    defaultNumber.value = {
      current: 0,
      total: 0
    };
    refreshStatusNumber.value = {
      current: 0,
      total: 0,
      refreshing: false
    };
  }

  // 获取状态
  // getStatusReq();

  onUnmounted(() => {
    // 清空定时器
    if (refreshingTimer) {
      clearInterval(refreshingTimer);
      refreshingTimer = null;
    }
  });

  return {
    isRefreshing,
    refreshStatusNumber,
    defaultNumber,
    handleStartRefresh
  };
};
